<template>
  <d2-container>
    <el-button
      type="primary"
      icon="el-icon-circle-plus-outline"
      @click="handleAdd"
      class="template-add"
      >新增项目
    </el-button>

    <!-- 表格 -->
    <el-table
      :data="tableList"
      :max-height="fullHeight"
      :row-class-name="tableRowClassName"
      v-loading="tableLoading"
    >
      <el-table-column width="80" prop="id" label="项目id"></el-table-column>
      <el-table-column width="200" prop="name" label="项目名"></el-table-column>
      <el-table-column width="100" prop="dbType" label="类型"></el-table-column>
      <el-table-column prop="dbUrl" label="jdbcUrl"></el-table-column>
      <el-table-column
        width="150"
        prop="description"
        label="描述"
      ></el-table-column>
      <el-table-column
        width="150"
        prop="packageName"
        label="包名"
      ></el-table-column>
      <el-table-column width="190" label="操作">
        <template slot-scope="{ row }">
          <el-popconfirm
            placement="top"
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            confirm-button-type="danger"
            title="确定删除吗？"
            @confirm="handleRemove(row)"
          >
            <el-button
              circle
              type="danger"
              slot="reference"
              size="small"
              icon="el-icon-delete"
              class="template-btn-delete"
            ></el-button>
          </el-popconfirm>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            circle
            @click="handleUpdate(row)"
          ></el-button>
          <el-button
            type="info"
            size="small"
            icon="el-icon-copy-document"
            circle
            @click="handleCopy(row)"
          ></el-button>
          <el-button
            type="warning"
            size="small"
            icon="el-icon-thumb"
            circle
            @click="handleLookTemplate(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 15, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :hide-on-single-page="true"
      v-if="tableList.length > 0"
      class="template-page"
    >
    </el-pagination>

    <!--  新增、编辑弹窗 -->
    <el-dialog
      :title="isAdd ? '新增项目' : '编辑项目'"
      :visible.sync="dialogFormVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :before-close="cancelDialogFormVisible"
      top="5vh"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="数据库名称" prop="name">
          <el-input placeholder="请输入数据库名称" v-model="form.name" />
        </el-form-item>
        <el-form-item label="数据库类型" prop="dbType">
          <el-select
            v-model="form.dbType"
            placeholder="请选择数据库类型"
            @change="changeDbType"
            style="width: 100%"
          >
            <el-option
              v-for="item in databaseTypeList"
              :key="item.dbType"
              :label="item.dbType"
              :value="item.dbType"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据库驱动" prop="dbDriver" v-show="form.dbType">
          <el-select
            v-model="form.dbDriver"
            placeholder="请选择数据库驱动"
            style="width: 100%"
          >
            <el-option
              v-for="item in databaseDriveList"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="jdbc url" prop="dbUrl">
          <el-input
            v-model="form.dbUrl"
            placeholder="例如：jdbc:mysql://127.0.0.1:3306/plume_code?characterEncoding=utf-8"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="dbUsername">
          <el-input v-model="form.dbUsername" />
        </el-form-item>
        <el-form-item label="密码" prop="dbPassword">
          <el-input v-model="form.dbPassword" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" />
        </el-form-item>
        <el-form-item label="表名前缀" prop="tablePrefix">
          <el-input v-model="form.tablePrefix" />
        </el-form-item>
        <el-form-item label="表属性前缀" prop="columnPrefix">
          <el-input v-model="form.columnPrefix" />
        </el-form-item>
        <el-form-item label="包名" prop="packageName">
          <el-input v-model="form.packageName" />
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button :loading="testing" type="primary" @click="test"
          >{{ testName }}
        </el-button>
        <el-button @click="submit">保存</el-button>
      </div>
    </el-dialog>
  </d2-container>
</template>

<script>
import api from "@/api";

export default {
  name: "template",
  data() {
    return {
      testing: false,
      testName: "测试连接",
      fullHeight: document.documentElement.clientHeight - 250,
      isAdd: false,
      dialogFormVisible: false,
      drawerVisible: false,
      previewContent: "",
      tableList: [],
      projectList: [],
      surfaceList: [],

      databaseTypeList: [],
      databaseDriveList: [],
      tableLoading: false,
      total: 0,
      pageSize: 10,
      currentPage: 1,
      form: {
        id: "",
        name: "",
        dbType: "",
        dbDriver: "",
        dbUrl: "",
        dbUsername: "",
        dbPassword: "",
        description: "",
        tablePrefix: "",
        columnPrefix: "",
        packageName: ""
      },
      rules: {
        name: [
          {
            required: true,
            message: "数据库名称",
            trigger: "blur"
          }
        ],
        dbType: [
          {
            required: true,
            message: "请选择数据库类型",
            trigger: "change"
          }
        ],
        dbDriver: [
          {
            required: true,
            message: "请选择数据库驱动",
            trigger: "blur"
          }
        ],
        dbUrl: [
          {
            required: true,
            message: "请输入jdbc url",
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    getTableList(this);
  },
  methods: {
    // 表格斑马线
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 >= 1) {
        return "select-row";
      }
      return "";
    },

    // 查看模板
    handleLookTemplate(row) {
      this.$router.push({
        name: "template",
        params: { projectId: row.id }
      });
    },

    // 表格分页
    handleSizeChange(val) {
      this.pageSize = val;
      getTableList(this);
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      getTableList(this);
    },

    // 根据数据库获取数据驱动
    changeDbType(value) {
      this.form.dbDriver = "";
      this.databaseDriveList = this.databaseTypeList.filter(
        item => item.dbType === value
      )[0].dbDriver;
    },

    // 删除项目
    handleRemove(row) {
      deleteProject(this, row);
    },

    // 新增模板按钮点击
    handleAdd() {
      this.isAdd = true;
      this.form.id = "";
      databaseType(this);
      this.dialogFormVisible = true;
    },

    // 编辑模板按钮点击
    handleUpdate(row) {
      this.isAdd = false;
      this.form.id = row.id;
      databaseType(this);
      updateInitProject(this, row.id);
      this.dialogFormVisible = true;
    },

    // 复制模板按钮点击
    handleCopy(row) {
      this.form.id = row.id;
      copyProject(this, row.id);
    },

    // 预览模板内容
    handlePreviewTemplate() {
      previewTemplateContent(this, { ...this.form });
      this.drawerVisible = true;
    },

    // 取消弹窗
    cancelDialogFormVisible() {
      this.$refs.formRef.resetFields();
      this.dialogFormVisible = false;
    },

    // 新增弹窗提交
    submit() {
      this.testing = true;
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.isAdd
            ? addProject(this, { ...this.form })
            : updateProject(this, { ...this.form });

          this.$refs.formRef.resetFields();
          this.dialogFormVisible = false;
        }
      });
      this.testing = false;
    },

    // 测试连接
    test() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.testing = false;
          this.testName = "测试中...";
          this.doTestConnection(this.form).then(res => {
            if (res == null) {
              this.$message.success("测试通过");
              this.form.isValid = true;
              this.testing = false;
              this.testName = "测试通过";
            } else {
              this.$message.warning(`测试未通过: ${res}`);
              this.form.isValid = false;
              this.testing = false;
              this.testName = "测试连接";
            }
          });
        }
      });
    },
    doTestConnection(data) {
      return api.testConnection(data);
    }
  }
};

// 项目列表
async function getTableList(that) {
  that.tableLoading = true;
  const data = {
    pageSize: that.pageSize,
    currentPage: that.currentPage
  };
  let res = await api.projectList(data);
  that.tableList = res || [];
  that.total = res.total;
  that.tableLoading = false;
}

// 新增项目
async function addProject(that, data) {
  let res = await api.projectAdd(data);
  getTableList(that);
  that.$message({
    message: "新增成功",
    type: "success"
  });
}

// 数据库类型
async function databaseType(that, data) {
  let res = await api.projectDatabaseType(data);
  that.databaseTypeList = res;
}

// 删除项目
async function deleteProject(that, data) {
  let res = await api.projectDelete(data);
  getTableList(that);
  that.$message({
    message: "删除成功",
    type: "success"
  });
}

// 复制
async function copyProject(that, data) {
  let res = await api.projectCopy(data);
  getTableList(that);
  that.$message({
    message: "复制成功",
    type: "success"
  });
}

// 编辑初始化
async function updateInitProject(that, data) {
  let res = await api.projectUpdateInit(data);
  that.form = { ...res };
  that.databaseDriveList = that.databaseTypeList.filter(
    item => item.dbType === res.dbType
  )[0].dbDriver;
}

// 编辑
async function updateProject(that, data) {
  let res = await api.projectUpdate(data);
  getTableList(that);
  that.$message({
    message: "修改成功",
    type: "success"
  });
}

// 测试连接
async function testConnection(that, data) {
  that.testing = true;
  that.testName = "测试中...";
  let res = await api.connectionTest(data);
  // isConnection 连接是否成功标志 true false
  alert(res);
  if (res) {
    that.$message.success("测试通过");
    that.testing = false;
    that.testName = "测试通过";
    return;
  }
  that.$message.warning(`测试未通过: ${res.msg}`);
  that.testing = false;
  that.testName = "测试连接";
}
</script>

<style lang="scss">
.el-table .select-row {
  background-color: #f3f6f9;
}

.template-add {
  margin-bottom: 15px;
}

.template-btn-delete {
  margin-right: 10px;
}

.template-select {
  width: 100%;
}

.template-preview-btn:hover {
  color: #fff;
}

.template-preview-content .el-drawer__open .el-drawer__header {
  margin-bottom: 0;
  padding: 15px 20px !important;
}

.template-preview-content .el-drawer__open .el-drawer__body {
  padding: 0px 20px 20px 20px;
  word-break: break-all;
  overflow: auto;
}

.template-velocity-params {
  margin-right: 20px;
  color: #1e90ff;
  font-weight: 800;
  text-decoration: underline;
  cursor: pointer;
}

.template-dialog .el-dialog__body {
  padding: 0 20px 20px 20px;
}

.template-velocity-title {
  font-weight: 900;
  font-size: 16px;
  margin-right: 10px;
}

.template-velocity-tip {
  font-size: 12px;
  color: #999;
}

.template-content {
  max-height: 380px;
  overflow: auto;
}

.el-tabs__content {
  overflow: auto;
  max-height: 530px;
}

.template-page {
  margin-top: 10px;
}
</style>
